<template>
  <div class="workstage_split">
    <el-dialog
      title="工序级拆分"
      width="1800px"
      :visible.sync="dialogTableVisible"
      v-dialogDrag
      :close-on-click-modal="false"
      customClass="mes_dialog"
      v-loading="isLoading"
      @closed="closedDialog">
      <!--<div class="dialog_content_title">
        <span class="alert_title center_layout">
          <i class="iconfont icon-tishi"></i>
          <i>拆分数量不能大于等于计划数量</i>
        </span>
      </div>-->
      <div class="base_msg">
        <div class="msg_item">
          <span>原周转码</span>
          <p>{{turnoverNumber}}</p>
        </div>
        <div class="msg_item">
          <span>原计划数量</span>
          <p>{{productionQuantity}}</p>
        </div>
        <div class="msg_item">
          <span>本次拆分数量</span>
          <p>
            <el-input-number
              :placeholder="'请输入本次拆分数量'"
              v-model="splitNum"
              :controls="false"
              :min="1"
              :max="productionQuantity"
              :precision="0">
            </el-input-number>
          </p>
        </div>
      </div>
      <div class="table_panel table_container">
        <el-table
          class="table_dialog"
          :data="listData"
          height="440"
          border
          style="width: 100%"
          tooltip-effect="dark"
          :cell-class-name="startDateIsError"
          :row-class-name="isFinished">
          <el-table-column
            show-overflow-tooltip
            :class-name="'static_col'"
            prop="sort"
            label="工序序号"
            align="center"
            width="80">
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            :class-name="'static_col'"
            prop="workstageName"
            label="工序名称"
            width="150">
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            prop="batchTechProcNumber"
            :class-name="'static_col'"
            label="工艺规程编号"
            align="center"
            width="150">
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            :class-name="'static_col'"
            prop="inspectionTypeLabel"
            label="检验类型"
            align="center"
            width="100">
          </el-table-column>
          <el-table-column
            prop="planStartDate"
            label="工序计划开始时间"
            align="center"
            width="160">
            <template slot-scope="scope">
              <div class="plane_time plane_startTime">
                <el-date-picker
                  :disabled="isDisabled(scope.row)"
                  :clearable="false"
                  v-model="scope.row.planStartDate"
                  align="right"
                  type="date"
                  placeholder="选择日期"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd 00:00:00"
                  :picker-options="getPickerOptionsStart(scope.row.planEndDate)"
                  class="start_date"
                >
                </el-date-picker>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="planEndDate"
            label="工序计划完成时间"
            align="center"
            width="160">
            <template slot-scope="scope">
              <div class="plane_time plane_endTime">
                <el-date-picker
                  :disabled="isDisabled(scope.row)"
                  :clearable="false"
                  v-model="scope.row.planEndDate"
                  align="right"
                  type="date"
                  placeholder="选择日期"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd 23:59:59"
                  :picker-options="getPickerOptionsEnd(scope.row.planStartDate)"
                  class="end_date">
                </el-date-picker>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :class-name="tableSelect"
            label="执行班组"
            prop="workgroupId"
            width="200">
            <template slot-scope="scope">
              <el-select
                :disabled="isDisabled(scope.row)"
                filterable
                placeholder="请选择执行班组"
                v-model="scope.row.workgroupId"
                class="type_list"
                :class="saveHandler&&!scope.row.workgroupId ? 'error_input':''"
                @change="workgroupChange(scope.row)">
                <el-option
                  v-for="item in scope.row.nametree"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            :class-name="tableSelect"
            prop="workcenterId"
            label="工作中心"
            width="200">
            <template slot-scope="scope">
              <el-select
                :disabled="isDisabled(scope.row)"
                filterable
                placeholder="请选择工作中心"
                v-model="scope.row.workcenterId"
                class="type_list"
                :class="saveHandler&&!scope.row.workcenterId ? 'error_input':''"
                @change="workcenterChange(scope.row)">
                <el-option
                  v-for="item in parseData(scope.row.nametree, scope.row.workgroupId, 'workcenter')"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            :class-name="tableSelect"
            prop="deviceIds"
            label="设备"
            width="200">
            <template slot-scope="scope">
              <el-select
                v-if="multipleStatus"
                :disabled="isDisabled(scope.row)"
                filterable
                multiple
                collapse-tags
                :multiple-limit="100"
                placeholder="请选择"
                v-model="scope.row.deviceIds"
                class="type_list">
                <el-option
                  v-for="item in parseData(parseData(scope.row.nametree, scope.row.workgroupId, 'workcenter'), scope.row.workcenterId, 'device')"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            :class-name="tableSelect"
            prop="staffIds"
            label="人员"
            width="200">
            <template slot-scope="scope">
              <el-select
                v-if="multipleStatus"
                :disabled="isDisabled(scope.row)"
                filterable
                multiple
                collapse-tags
                :multiple-limit="100"
                placeholder="请选择"
                v-model="scope.row.staffIds"
                class="type_list">
                <el-option
                  v-for="item in parseData(parseData(scope.row.nametree, scope.row.workgroupId, 'workcenter'), scope.row.workcenterId, 'staff')"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            :class-name="'static_col'"
            prop="assignRule"
            label="派工规则"
            align="center"
            width="100">
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            :class-name="'static_col'"
            prop="estimateEffort"
            label="定额工时"
            align="center"
            width="80">
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            :class-name="'static_col'"
            prop="workstageRemarks"
            label="工序描述">
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            :class-name="'static_col'"
            prop="workstageSummary"
            label="工序简述">
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer mes_btn">
        <el-button type="primary" @click="saveData" :disabled="submitDisabled">提交</el-button>
        <el-button @click="dialogTableVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'WorkstageSplit',
  data() {
    return {
      dialogTableVisible: false,
      saveHandler: false, // 是否已经触发点击保存事件
      multipleStatus: false,
      tableSelect: 'table_select',
      isLoading: false, // 表格初始化loading
      turnoverId: '', // 原周转ID
      turnoverNumber: '', // 原周转码
      productionQuantity: 0, // 计划数量
      splitNum: null, // 拆分数量
      saveStatus: true, // 保存禁用
    }
  },
  computed: {
    // 表格列表
    listData() {
      return this.$store.state.workSheetManage.workstageSplitList.turnoverWorkstageList || []
    },
    // 树形列表
    treeList() {
      return this.$store.state.workSheetManage.treeList
    },
    // 当前0点0分0秒时间戳
    todayMillisecond() {
      return this.moment(window.serverTime).startOf('day').unix() * 1000
    },
    // 工单计划开始时间
    planStartDate() {
      return this.$store.state.workSheetManage.workstageSplitList.planStartTime || ''
    },
    // 工单计划完成时间-最大选择范围
    planEndDate() {
      return this.$store.state.workSheetManage.workstageSplitList.planEndTime || ''
    },
    // 工序进度状态
    workstageProcessStatus() {
      let list = this.$store.state.dict.workstageProcessStatusType.labels || []
      return this.addLabelAll(list)
    },
    // 提交状态
    submitDisabled() {
      return !this.listData.some((item) => item.workstageProcessStatusValue !== 'Finished')
    }
  },
  methods: {
    // 初始化表格
    init(list) {
      this.dialogTableVisible = true
      this.isLoading = true
      this.turnoverId = list[0].id
      this.turnoverNumber = list[0].number
      this.productionQuantity = list[0].productionQuantity
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/turnoverbatch/turnoverBatch/prepareSplit',
        data: {turnoverId: this.turnoverId},
        module: 'workSheetManage',
        state: 'workstageSplitList'
      }).finally(() => {
        this.isLoading = false
        this.multipleStatus = true
      })
    },
    /**
     * 解析树形子集，如选择工厂时获取所选工厂下的车间列表
     * @param {Array} list 父集列表
     * @param {String} id 所选父集元素id
     * @param {Array} field 表示子集的字段名称，如：workshops（车间）
     * @returns {Array}
     */
    parseData(list, id, field) {
      let result = list.find(value => value.id === id)
      if (result) {
        return list.find(value => value.id === id)[field] || []
      } else {
        return []
      }
    },
    // 班组选择切换
    workgroupChange(row) {
      this.listData.forEach((item) => {
        if (item.id === row.id && item.workcenterId) {
          item.workcenterId = ''
          item.deviceIds = []
          item.staffIds = []
        }
      })
    },
    // 工作中心切换
    workcenterChange(row) {
      this.listData.forEach((item) => {
        if (item.id === row.id && item.workcenterId) {
          item.deviceIds = []
          item.staffIds = []
        }
      })
    },
    // 计划开始\结束时间是否错误，返回错误样式名称
    startDateIsError({row}) {
      let start = row.planStartDate || row.startDate
      let end = row.planEndDate || row.endDate
      let result = ''
      if (this.moment(start).isBefore(this.todayMillisecond)) {
        result = 'error_date_start'
      }
      if (this.moment(end).isBefore(this.todayMillisecond)) {
        result = result + ' error_date_end'
      }
      return result
    },
    /**
     * 开始时间输入限定（周转表/工序表）
     * @param currentEnd 工序计划完成时间（周转/工序）
     */
    getPickerOptionsStart(currentEnd) {
      let date = currentEnd || new Date()
      const minMillisecond = this.todayMillisecond
      const maxMillisecond = this.moment(date).unix() * 1000
      return {
        // 工序计划开始时间不能小于当前时间且不能大于计划完成时间
        disabledDate(time) {
          if (currentEnd) {
            return time.getTime() < minMillisecond || time.getTime() > maxMillisecond
          } else {
            return time.getTime() < minMillisecond
          }
        }
      }
    },
    /**
     * 完成时间输入限定（周转表/工序表）
     * @param currentStart 工序计划开始时间（周转/工序）
     */
    getPickerOptionsEnd(currentStart) {
      let start = this.todayMillisecond
      // 对比是否有计划开始时间以及计划开始时间是否在当前时间之后
      if (currentStart && this.moment(currentStart).isAfter(this.todayMillisecond)) {
        start = this.moment(currentStart).unix() * 1000
      }
      const minMillisecond = this.moment(start).subtract(1, 'days').unix() * 1000 + 1
      return {
        // 工序计划完成时间不能小于工序计划开始时间和当前时间
        disabledDate(time) {
          return time.getTime() < minMillisecond
        }
      }
    },
    // 判断是否是已完成的工序进度返回表格样式
    isFinished({row}) {
      let id = row.workstageProcessStatusId
      let list = this.workstageProcessStatus
      let item = list.find((item) => item.id === id)
      if (item) {
        return item.value === 'Finished' ? 'row_isFinished' : ''
      }
    },
    // 判断是否是已完成的工序进度返回选择禁用
    isDisabled(row) {
      let id = row.workstageProcessStatusId
      let list = this.workstageProcessStatus
      let item = list.find((item) => item.id === id)
      if (item) {
        return item.value === 'Finished'
      }
    },
    // 保存数据
    saveData() {
      if (!this.splitNum) {
        return this.tipMessage('error', '本次拆分数量不能为空')
      }
      if (this.splitNum >= this.productionQuantity) {
        return this.tipMessage('error', '本次拆分数量只能小于计划数量')
      }
      if (this.listData.some((item) => !item.workgroupId)) {
        return this.tipMessage('error', '执行班组不能为空')
      }
      if (this.listData.some((item) => !item.workcenterId)) {
        return this.tipMessage('error', '工作中心不能为空')
      }
      let postData = JSON.parse(JSON.stringify(this.listData))
      console.log(JSON.parse(JSON.stringify(this.listData)))
      postData.forEach((item) => {
        if (Array.isArray(item.staffIds)) {
          item.staffIds = item.staffIds.join(',')
          console.log(item.staffIds)
        }
        if (Array.isArray(item.deviceIds)) {
          item.deviceIds = item.deviceIds.join(',')
        }
      })
      if (this.saveStatus) {
        this.saveStatus = false
        this.$store.dispatch('saveData', {
          method: 'post',
          url: 'a/turnoverbatch/turnoverBatch/turnoverBatchSplit',
          data: {
            turnoverId: this.turnoverId,
            splitNum: Number(this.splitNum),
            turnoverWorkstageList: postData
          },
          noCommit: true
        }).then(() => {
          this.tipMessage('success', '拆分成功')
          this.dialogTableVisible = false
          this.$emit('submitSuccess')
        }).catch(() => {
          this.saveStatus = true
        })
      }
    },
    // 关闭dialog
    closedDialog() {
      this.saveStatus = true
      this.splitNum = null
      this.multipleStatus = false
    },
    /**
     * 提示
     * @param type 提示类型
     * @param str 提示内容
     */
    tipMessage(type, str) {
      this.$message({
        type: type,
        message: str,
        duration: 1500,
        center: true
      })
    }
  }
}
</script>

<style lang="less">
  .workstage_split {
    .base_msg {
      display: flex;
      text-align: center;
      border: @mesBorDefault;
      border-top: none;
      margin-bottom: 20px;

      .msg_item {
        width: 33.33333333333333333333333333333%;
        display: flex;
        line-height: 40px;

        &:nth-child(1) span {
          border-left: none;
        }

        span {
          width: 200px;
          background-color: #ebf0f6;
          color: #000;
          border-left: @mesBorDefault;
          border-right: @mesBorDefault;
          font-weight: bold;
          border-top: @mesBorDefault;
        }

        p {
          background-color: #f5f5f5;
          color: #333333;
          width: calc(100% - 200px);
          overflow: hidden;
          height: 40px;
          border-top: @mesBorDefault;

          .el-input-number {
            width: 100%;
            height: 100%;
            top: -2px;

            .el-input {
              width: 100%;
              height: 100%;
            }
          }

          .el-input__inner {
            position: absolute;
            top: 2px;
            left: 0;
            border: none;

            &.error_input {
              color: @mesTableInputEFC;
            }

            &:focus {
              // border: @mesTableInputFBorder;
            }
          }
        }
      }
    }

    .table_panel {
      padding: 0 !important;

      .el-tabs__header {
        margin-bottom: 0;
      }

      .el-table--border {
        margin: 0 !important;

        .el-table-column--selection .cell {
          padding: 0;
        }
      }

      .el-table__body td {
        padding: 0;

        .cell {
          white-space: nowrap;
          line-height: 40px;
          padding: 0 10px;

          .icon-td_date {
            font-weight: 600;
            padding-left: 10px;
          }
        }

        &.table_select {
          .cell {
            padding: 0 !important;

            .el-input__inner {
              padding: 0 10px !important;
            }
          }
        }
        .el-input__inner {
          outline: none;
          border: none !important;
          background-color: transparent !important;
          padding-right: 14px !important;
          text-overflow: ellipsis;
        }

        .el-input__prefix {
          left: -6px;
        }

        .type_list {
          width: 100%;

          .el-input__inner {
            padding-left: 0;
          }

          &.error_input {
            .el-input__inner {
              color: @mesTableInputEFC;
            }
          }
        }
      }
    }

    .plane_time {
      .el-input__icon {
        color: @mesTableDateIconC;
        font-weight: 600;
      }
    }

    .el-table tr.row_isFinished {
      td {
        background-color: #f5f7fa;
      }

      .plane_time {
        .el-input__icon {
          color: #a1b1c1;
          font-weight: 600;
        }
      }
    }
  }
</style>
